import { defineStore } from "pinia"
import { request } from '@/common/fetch'
import { DOMAIN, PATH } from "@/common/api"
import { objToParam, bindActionCreators } from "@/common/unite"
import { MainInterface } from "@/interface"
import { MAIN } from "@/constant"

export const useMainStore = defineStore("main", {
  state: (): MainInterface.useMainState => ({
    bookList: []
  }),
  actions: {
    [MAIN.GETMAINPOST_SUCCESS]: function (payload: ObjectType) {
      this.$patch(state => {
        state.bookList = payload.info
      })
    }    
  }
})

export const getMainPost: ({ option }: MainInterface.GetMainPost) => Promise<any> = ({ option }) => bindActionCreators({
  type: MAIN.GETMAINPOST_SUCCESS,
  fetchApi: () => request(`${DOMAIN.TYPICODE}${PATH.POSTS.QUERYPOSTS}?${objToParam(option)}`),
  pipe: (json: ObjectType) => ({
    info: json ?? []
  })
}, useMainStore())

export const getMainPostDetial: ({ option }: MainInterface.GetMainPost) => Promise<any> = ({ option, ...restparams }) => bindActionCreators({
  fetchApi: () => request(`${DOMAIN.TYPICODE}${PATH.POSTS.QUERYPOSTS}/${option.userId}`),
  pipe: (json: ObjectType) => ({
    info: json ?? []
  }),
  ...restparams
}, useMainStore())

export const putMainPostDetial: ({ option }: MainInterface.PutMainPost) => Promise<any> = ({ option, ...restparams }) => bindActionCreators({
  fetchApi: () => request(`${DOMAIN.TYPICODE}${PATH.POSTS.QUERYPOSTS}/${option.userId}`, {
    method: 'PUT',
    headers: {
      'Content-type': 'application/json; charset=UTF-8',
    },
    body: JSON.stringify(option)
  }),
  pipe: (json: ObjectType) => ({
    info: json ?? {}
  }),
  ...restparams
}, useMainStore())